package com.tycmc.signelectroniccontracts.tools.base;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.tycmc.signelectroniccontracts.R;
import com.tycmc.signelectroniccontracts.tools.manager.AppInfo;
import com.tycmc.signelectroniccontracts.tools.manager.AppManager;
import com.tycmc.signelectroniccontracts.tools.manager.StatusBarCompat;


/**
 * Created by Administrator on 2017/2/21 0021.
 */

public abstract class ActBase extends FragmentActivity {

    /**
     * # 获取屏幕亮度
     *
     * @return
     */

    public int getScreenBrightness() {
        int value = 0;
        ContentResolver cr = getContentResolver();
        try {
            value = Settings.System.getInt(cr,
                    Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {

        }
        return value;
    }

    /**
     * # 设置屏幕亮度
     *
     * @param value
     */
    public void setScreenBrightness(int value) {
        WindowManager.LayoutParams params = getWindow()
                .getAttributes();
        params.screenBrightness = value / 255f;
        getWindow().setAttributes(params);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AppManager.getAppManager().addActivity(this);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.status_color_head));
        StatusBarCompat.setStstus(this, true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (findViewById(R.id.iv_back) != null) {
            findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    exit();
                }
            });
        }
    }

    public void setTitleText(String title) {
        if (findViewById(R.id.tv_title) != null) {
            ((TextView) findViewById(R.id.tv_title)).setText(title);
        }
    }

    public String getTitleText() {
        if (findViewById(R.id.tv_title) != null) {
            return ((TextView) findViewById(R.id.tv_title)).getText().toString().trim();
        }
        return "";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (ActBase.onActivityResultCallBack != null)
            ActBase.onActivityResultCallBack.onResult(requestCode, resultCode, data);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (ActBase.permissionsResultCallBack != null)
            ActBase.permissionsResultCallBack.onRequestPermissionResult(requestCode, permissions, grantResults);
    }

    public static OnActivityResultCallBack onActivityResultCallBack;

    public void setOnActivityResultCallBack(OnActivityResultCallBack onActivityResultCallBack) {
        ActBase.onActivityResultCallBack = onActivityResultCallBack;
    }

    /**
     * 接收回传值
     */
    public interface OnActivityResultCallBack {
        void onResult(int requestCode, int resultCode, Intent data);
    }

    public static OnRequestPermissionsResultCallBack permissionsResultCallBack;

    public void setOnPermissionsResultCallBack(OnRequestPermissionsResultCallBack permissionsResultCallBack) {
        ActBase.permissionsResultCallBack = permissionsResultCallBack;
    }

    /**
     * 接收权限申请的回调
     */
    public interface OnRequestPermissionsResultCallBack {
        void onRequestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
    }

    /**
     * 点击输入框以外的区域隐藏键盘
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInputView();
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                if (imm != null) {
//                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//                    v.clearFocus();
//                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    /**
     * 检测屏幕变化的大小
     */
    public void setHightChangeListen(final OnHightChangeLister changeListen) {
        final View mRoot = getWindow().getDecorView();
        mRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                mRoot.getWindowVisibleDisplayFrame(rect);
                int rootInvisibleHeight = mRoot.getRootView().getHeight() - rect.bottom;
                changeListen.hightChange(rootInvisibleHeight, AppInfo.getVirtualBarHeigh(ActBase.this));
            }
        });
    }

    public interface OnHightChangeLister {
        void hightChange(int change, int virtualBarHeigh);//屏幕变化的高度，虚拟键的高度
    }

    /**
     * 全屏
     */
    public void fullScreen() {
        Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    }

    /**
     * 隐藏虚拟状态栏
     */
    public void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

    /**
     * 设置透明状态栏
     */
    public void transparentStatusbar() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
            );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0x00000000);
            window.setNavigationBarColor(0x00000000);
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 隐藏软键盘 hideSoftInputView
     */
    public void hideSoftInputView() {
        try {
            InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
            if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                if (getCurrentFocus() != null)
                    manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示键盘
     */
    public void showSoftInputView() {
        InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext().
                getSystemService(this.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }


    /**
     * 跳转添加动画
     *
     * @param intent    跳转的事件
     * @param enterAnim 跳转的进入动画
     * @param exitAnim  跳转的退出动画
     */
    public void start(Intent intent, int enterAnim, int exitAnim) {
        startActivity(intent);
        overridePendingTransition(enterAnim, exitAnim);
    }

    /**
     * 跳转默认动画
     *
     * @param intent
     */
    public void start(Intent intent) {
        startActivity(intent);
    }

    /**
     * 退出的默认动画
     * 退出
     */
    public void exit() {
        hideSoftInputView();
        finish();
    }

    /**
     * 退出添加动画
     *
     * @param enterAnim 退出界面的进入动画
     * @param exitAnim  退出界面时退出动画
     */
    public void exit(int enterAnim, int exitAnim) {
        finish();
        overridePendingTransition(enterAnim, exitAnim);
    }
}
